$(function() {
	// 初始化组织树
	initZtree();
	// initUnbindUser();
	// initGridUnbindUser();
});
var level;
var serverUserBindHirencyData = {};// 用户绑定了组织的数据
var serverUserBindHirencyTable;// 用户绑定了组织的表

// 初始化 层级树
var primaryNode = [];

var modalSetting = {
	edit : {
		enable : true,
		showRemoveBtn : false,
		showRenameBtn : false,
		drag : {
			isCopy : false,
			isMove : true,
			prev : true,
			next : true,
			inner : true
		}
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "parentId",
			rootParentId : 0
		}
	},
	view : {
		showLine : true
	},
	check : {
		enable : true,
		chkStyle : "radio",
		radioType : "level"
	},
	callback : {
		onClick : showBindHierarchyPrepare,// 绑定组织的用户
		onCheck : editNewModule
	}
};
// =======================网格与用户解绑=========================
$(".unbindBtn").click(function() {
	// 获取勾选的网格
	var gridIds = '';
	$(".selectAllBindGrid").each(function() {
		if ($(this).prop("checked") == true) {
			gridIds += $(this).attr("ownId") + ",";
		}
	});
	var userId = $("#unbindUserId").val();
	if (gridIds == '') {
		message("请勾选要解除绑定的网格!");
		return false;
	}
	$("#right").mLoading("show");
	$.ajax({
		url : rootPath + "/ui/userDimension/unbind/" + gridIds + "/" + userId,
		dataType : 'json',
		type : 'post',
		success : function(result) {
			if (result.code == 1) {
				message("解除绑定成功!");
				serverGridUnbindUserData.key = '';
				serverGridUnindUserTable.draw();

				serverGridBindUserData.key = userId;
				serverGridBindUserTable.draw();
			}
			$("#right").mLoading("hide");
		}
	});
});
// =======================网格与用户绑定=========================
$(".bindUser").click(function() {
	// 获取勾选的网格
	var gridIds = '';
	$(".selectAllUnbindGrid").each(function() {
		if ($(this).prop("checked") == true) {
			gridIds += $(this).attr("ownId") + ",";
		}
	});
	if (gridIds == '') {
		message("请勾选要绑定的网格!");
		return false;
	}
	var userId = $("#bindUserId").val();
	if (userId == '') {
		message("请点击用户姓名进行绑定!");
		return false;
	}
	$("#right").mLoading("show");
	$.ajax({
		url : rootPath + "/ui/userDimension/bind/" + userId + "/" + gridIds,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				message("绑定成功!");
				serverGridUnbindUserData.key = '';
				serverGridUnindUserTable.draw();

				serverGridBindUserData.key = userId;
				serverGridBindUserTable.draw();
			}
			$("#right").mLoading("hide");
		}
	});
});
// ======================初始化未绑定用户的网格==========================
$(".searchBtn2").click(function() {
	serverGridUnbindUserData.key = $("#search2").val();
	var userId = $("#userId").val();
	if (userId == '') {
		userId = '0';
	}

	serverGridUnbindUserData.uid = userId;
	serverGridUnindUserTable.draw();
});
$(".resetBtn2").click(function() {
	$("#search2").val('');
	serverGridUnbindUserData.key = '';
	serverGridUnbindUserData.key = $("#search2").val();
	var userId = $("#userId").val();
	if (userId == '') {
		userId = '0';
	}

	serverGridUnbindUserData.uid = userId;
	serverGridUnindUserTable.draw();
});
var serverGridUnbindUserData = {};// 用户未绑定组织的数据
var serverGridUnindUserTable;// 用户未绑定组织的表

function initGridUnbindUser(id) {

	$("#selectAllUnbindGrid").click(function() {
		var state = $(this).prop("checked");
		$(".selectAllUnbindGrid").prop("checked", state);
	});

	serverGridUnindUserTable = jQuery('#gridUnbindUserGridTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "post",
							"cache" : false,
							"url" : window.rootPath
									+ '/ui/userDimension/getGridUnbindUserPage',
							"data" : function(d) {
								return $
										.extend({}, d, serverGridUnbindUserData);
							}
						},
						columns : [
								{
									data : null,
									defaultContent : ""
								},
								{
									data : 'id',
									defaultContent : "",
									render : function(data, type, full, meta) {

										var operate = "<input type='checkbox' class='selectAllUnbindGrid' ownId='"
												+ data + "'/>";
										return operate;
									}
								}, {
									data : 'gridIdentify'
								}, {
									data : 'gridName'
								} ],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length
									+ oSettings._iDisplayStart;
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$(
										'td:eq(0)',
										oSettings.aoData[oSettings.aiDisplay[k]].nTr)
										.text(i + 1);
								k++;
							}
							serverGridUnindUserTable.off('click', 'tr');

						}
					});
}

// ================================初始化绑定用户的网格========================
$(".searchBtn3").click(function() {
	serverGridBindUserData.con = $("#search3").val();
	var userId = $("#userId").val();
	if (userId == '' || userId == null) {
		userId = '0';
	}
	serverGridBindUserData.key = userId;
	serverGridBindUserTable.draw();
});
$(".resetBtn3").click(function() {
	$("#search3").val('');
	var userId = $("#userId").val();
	if (userId == '' || userId == null) {
		userId = '0';
	}
	serverGridBindUserData.key = userId;
	serverGridBindUserData.con = '';
	serverGridBindUserTable.draw();
});
var serverGridBindUserData = {};// 用户绑定了组织的数据
var serverGridBindUserTable;// 用户绑定了组织的表

function initGridBindUser(id) {

	$("#selectAllBindGrid").click(function() {
		var state = $(this).prop("checked");
		$(".selectAllBindGrid").prop("checked", state);
	});
	serverGridBindUserTable = jQuery('#gridBindGridTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "post",
							"cache" : false,
							"url" : window.rootPath
									+ '/ui/userDimension/getGridBindUserPage',
							"data" : function(d) {
								return $.extend({}, d, serverGridBindUserData);
							}
						},
						columns : [
								{
									data : null,
									defaultContent : ""
								},
								{
									data : 'id',
									defaultContent : "",
									render : function(data, type, full, meta) {

										var operate = "<input type='checkbox' class='selectAllBindGrid' ownId='"
												+ data + "'/>";
										return operate;
									}
								}, {
									data : 'gridIdentify'
								}, {
									data : 'gridName'
								}, {
									data : 'gridArea'
								}, {
									data : 'gridState.title'
								}, {
									data : 'typeOpt.title'
								}, {
									data : 'gridToArcGisObjectId'
								}, {
									data : "division.divisionName"
								} ],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length
									+ oSettings._iDisplayStart;
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$(
										'td:eq(0)',
										oSettings.aoData[oSettings.aiDisplay[k]].nTr)
										.text(i + 1);
								k++;
							}
							serverGridBindUserTable.off('click', 'tr');

						}
					});

};
function editNewModule(e, treeId, treeNode) {
	// 预留
};
function showBindHierarchyPrepare(e, treeId, treeNode) {

	var hierarchyId = treeNode.id;

	serverUserBindHirencyData.key = hierarchyId;
	initUserPage(hierarchyId);
	serverGridBindUserData.key = '';
	if (serverGridBindUserTable) {
		serverGridBindUserTable.draw(false);
	}

	serverGridUnbindUserData.uid = '';
	if (serverGridUnindUserTable) {
		serverGridUnindUserTable.draw();
	}

	serverUserBindHirencyTable.draw();

};
// ===========================绑定组织的用户===========================
$(".searchBtn1").click(function() {
	serverUserBindHirencyData.con = $("#search1").val();
	var treeObj = $.fn.zTree.getZTreeObj("hierarchyTree");
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode) {
			serverUserBindHirencyData.key = selectNode.id;
		}
	} else {
		serverUserBindHirencyData.key = "0";
	}
	serverUserBindHirencyTable.draw();
});
$(".resetBtn1").click(function() {
	$("#search1").val('');
	serverUserBindHirencyData.con = '';
	serverUserBindHirencyTable.draw();
});
function initUserPage(hierarchyId) {
	serverUserBindHirencyTable = $('#userBindHierarchyTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "get",
							"cache" : false,
							"url" : window.rootPath
									+ '/ui/userDimension/getUserBindHierarchyPage',
							"data" : function(d) {
								return $.extend({}, d,
										serverUserBindHirencyData);
							}
						},
						columns : [
								{
									data : null,
									defaultContent : ""
								},
								{
									data : 'name',
									render : function(data, type, full, meta) {
										return "<a style='cursor:pointer' class='aClick'>"
												+ data + "</a>";
									}

								}, {
									data : 'sex'
								}, {
									data : 'hierarchy.groupName'
								} ],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length
									+ oSettings._iDisplayStart;
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$(
										'td:eq(0)',
										oSettings.aoData[oSettings.aiDisplay[k]].nTr)
										.text(i + 1);
								k++;
							}
							serverUserBindHirencyTable.off('click', 'tr');

							serverUserBindHirencyTable
									.on(
											'click',
											'tr',
											function(event) {
												event = event || window.event;
												var target = event.target
														|| event.scrElement;
												var data = serverUserBindHirencyTable
														.row(this).data();

												if (target.className
														.indexOf('aClick') != -1) {
													// 初始化绑定用户的网格
													serverGridBindUserData.key = data.id;
													$("#userId").val(data.id);
													$("#bindUserId").val(
															data.id);
													$("#unbindUserId").val(
															data.id);
													initGridBindUser(data.id);
													serverGridBindUserTable
															.draw();

													serverGridUnbindUserData.uid = data.id;
													initGridUnbindUser(data.id);
													serverGridUnindUserTable
															.draw();
												}

												return;
											});
						}
					});

};
// ==============================初始化组织树===========================
function initZtree() {

	$.ajax({
		url : rootPath + "/ui/userDimension/initHierarchyTree",
		cache : false,
		type : "get",
		data : '',
		dataType : "json",
		contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
		success : function(data) {
			primaryNode.push({
				id : 0,
				name : "组织层级",
				open : "true"
			// iconSkin:"diy03"
			});
			for (var i = 0; i < data.nodes.length; i++) {
				primaryNode.push(data.nodes[i]);
			}
			$.fn.zTree.init($("#hierarchyTree"), modalSetting, primaryNode);
		}
	});
};
